package org.wlw.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.wlw.mapper.MovieMapper;
import org.wlw.models.Movie;
import org.wlw.models.WlwSystemException;
import org.wlw.service.IMovieService;
import org.wlw.utils.DBUtils;
import java.util.List;

public class MovieService implements IMovieService {

    @Override
    public void add(Movie movie) {
        if(movie.getName().length()<=2) {
            throw new WlwSystemException("添加的电影名称不正确!");
        }
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(MovieMapper.class).add(movie);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public void delete(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(MovieMapper.class).delete(id);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public void update(Movie movie) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(MovieMapper.class).update(movie);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public Movie load(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return sqlSession.getMapper(MovieMapper.class).load(id);
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public List<Movie> find() {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return sqlSession.getMapper(MovieMapper.class).find();
        } finally {
            DBUtils.close(sqlSession);
        }
    }
}
